#include "c/thermocouple.h"
#include "c/spi.h"

#include <avr/io.h>

#define TC_MAX6675
#define TC_MAX31855

#define TC_CS_PORTx PORTD
#define TC_CS_DDRx DDRD
#define TC_CS_PIN 2

void tc_init()
{
	// setup pin(s)
	TC_CS_DDRx |= _BV(TC_CS_PIN);
	TC_CS_PORTx |= _BV(TC_CS_PIN);
}

double tc_read()
{
	double result = 0.0;
	
	spi_mode(SPI_MODE_TCIC);
	
	TC_CS_PORTx &= ~_BV(TC_CS_PIN);
	
	#ifdef TC_MAX6675
	
	uint16_t raw = spi_tx(0) << 8;
	raw |= spi_tx(0);
	
	#elif defined(TC_MAX31855)
	
	uint32_t raw = spi_tx(0) << 24;
	raw |= spi_tx(0) << 16;
	raw |= spi_tx(0) << 8;
	raw |= spi_tx(0);
	
	#endif
	
	raw >>= 2;
	
	result = raw;
	result /= 4;
	
	TC_CS_PORTx |= _BV(TC_CS_PIN);
	
	return result;
}